﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using IRUM.Core;
using IRUM.XingAPI;
using IRUM.Utils;
using System.Threading;

namespace IRUM.TR
{
    /// <summary>
    /// 선물옵션 과거데이터시간대별조회
    /// </summary>
    public class ChartForeignData
    {
        public string kind = string.Empty;
        public string shcode = string.Empty;
        public string gubun = string.Empty;
        public string date = string.Empty;  //"yyyymmdd"
        public string time = string.Empty;  //"hhmmss"
        public float open = 0;
        public float high = 0;
        public float low = 0;
        public float close = 0;
        public float volume = 0;
        public string kodate = string.Empty;
        public string kotime = string.Empty;
    }

    public class ChartForeignDataArgs : EventArgs
    {
        public List<ChartForeignData> RetData = null;

        public ChartForeignDataArgs(List<ChartForeignData> data)
        {
            RetData = data;
        }
    }

    public delegate void ChartForeignDataHandler(object s, ChartForeignDataArgs e);
    
    /// <summary>
    /// 해외지수 일/분 차트
    /// </summary>
    public class t3518 : CBaseQuery
    {
        public event ChartForeignDataHandler OnReceived;
        private List<ChartForeignData> m_list = new List<ChartForeignData>();

        private string kind = string.Empty;
        private string shcode = string.Empty;
        private string gubun = "0";     //0:일, 1:주, 2:월, 3:분, 4:틱
        private string lastDBDate = string.Empty;
        private string cts_date = string.Empty;
        private string cts_time = string.Empty;

        private string lastDataDate = string.Empty; //없는 데이터만 받기 위해 사용

        /// <summary>
        /// 해외지수 일/분 차트
        /// <param name="kind">종목종류, S:해외지수, F:해외선물, R:환율/금리</param>
        /// <param name="shcode">종목코드</param>
        /// <param name="gubun">일/분구분, D:일, M:분</param>
        /// <param name="lastDBDate">DB에 저장되어 있는 마지막 날짜</param>
        /// </summary>
        public t3518(string kind, string shcode, string gubun, string lastDBDate)
        {
            this.kind = kind;
            this.shcode = shcode;
            this.gubun = gubun;
            this.lastDBDate = lastDBDate;

            SetClassData(TR_Type.t3518);
        }

        public void SetOutBlockData(int Index)
        {
            lastDataDate = m_Query.GetFieldData(m_OutBlock1Name, "date", Index);

            if (Convert.ToInt32(lastDataDate) > Convert.ToInt32(lastDBDate))
            {
                ChartForeignData cd = new ChartForeignData();
                cd.kind = kind;
                cd.shcode = shcode;
                cd.gubun = gubun;
                cd.date = m_Query.GetFieldData(m_OutBlock1Name, "date", Index);
                cd.time = m_Query.GetFieldData(m_OutBlock1Name, "time", Index);
                cd.open = Convert.ToSingle(m_Query.GetFieldData(m_OutBlock1Name, "open", Index));
                cd.high = Convert.ToSingle(m_Query.GetFieldData(m_OutBlock1Name, "high", Index));
                cd.low = Convert.ToSingle(m_Query.GetFieldData(m_OutBlock1Name, "low", Index));
                cd.close = Convert.ToSingle(m_Query.GetFieldData(m_OutBlock1Name, "price", Index));
                cd.volume = Convert.ToSingle(m_Query.GetFieldData(m_OutBlock1Name, "volume", Index));
                cd.kodate = m_Query.GetFieldData(m_OutBlock1Name, "kodate", Index);
                cd.kotime = m_Query.GetFieldData(m_OutBlock1Name, "kotime", Index);

                m_list.Add(cd);
            }
        }

        public override void HandleQuery()
        {
            int OccursCount = m_Query.GetBlockCount(m_OutBlock1Name);

            for (int OccursIndex = 0; OccursIndex < OccursCount; OccursIndex++)
            {
                try
                {
                    SetOutBlockData(OccursIndex);
                }
                catch (Exception e)
                {
                    Debug.Print(e.ToString());
                    continue;
                }
            }

            //연속조회 - 환율은 분단위 조회 시 같은 데이터가 무한 반복 들어옴, 다우지수의 경우 데이터가 없는데도 연속조회가 되는 문제가 있음.
            if (OccursCount > 0 && m_Query.IsNext == true && (kind.Equals("R") == false || gubun.Equals("D") == true) && Convert.ToInt32(lastDataDate) > Convert.ToInt32(lastDBDate))
            {
                cts_date = m_Query.GetFieldData(m_OutBlockName, "cts_date", 0);
                cts_time = m_Query.GetFieldData(m_OutBlockName, "cts_time", 0);

                Thread.Sleep(1000);
                RequestNext();
            }
            else
            {
                // 이벤트 발생
                if (OnReceived != null)
                {
                    OnReceived(this, new ChartForeignDataArgs(m_list));
                }
            }
        }

        protected override void SetRequestData()
        {
            string jgbn = string.Empty;

            switch (gubun)
            {
                case "D":
                    jgbn = "0";
                    break;
                case "M":
                    jgbn = "3";
                    break;
            }

            m_Query.SetFieldData(m_InBlockName, "kind", 0, kind);            //종목종류, 1, S:해외지수, F:해외선물, R:환율/금리
            m_Query.SetFieldData(m_InBlockName, "symbol", 0, shcode);        //종목코드, 16, 빈칸을 space로 채워야 조회됨
            m_Query.SetFieldData(m_InBlockName, "cnt", 0, "500");            //입력건수, 4, 안넣으면 조회가 이상하게 됨
            m_Query.SetFieldData(m_InBlockName, "jgbn", 0, jgbn);           //조회구분, 1, 0:일, 1:주, 2:월, 3:분, 4:틱
            m_Query.SetFieldData(m_InBlockName, "nmin", 0, "1");             //N분, 3, jgbn이 3인 경우 n분
            m_Query.SetFieldData(m_InBlockName, "cts_date", 0, cts_date);    //연속날짜, 8, 처음 조회시 Space, 다음 조회시 OutBlock의 cts_date 값 입력
            m_Query.SetFieldData(m_InBlockName, "cts_time", 0, cts_time);    //연속시간, 6, 처음 조회시 Space, 다음 조회시 OutBlock의 cts_time 값 입력
        }
    }
}
